package com.example.goover;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * ClassName: ConsumerPartitioner
 * Package: com.example.goover
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-05
 * Time: 19:44
 */


//消费指定分区
public class ConsumerPartitioner {

    public static void main(String[] args) {

        //0.创建配置文件
        Properties properties = new Properties();

        //配置必要信息
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"hadoop102:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());

        //设置消费者组ID
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test");

        //1.创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //消费指定分区 调用assign 参数是一个TopicPartition类型的集合
        ArrayList<TopicPartition> topicPartitions = new ArrayList<>();

        topicPartitions.add(new TopicPartition("first",0));
        //调用assign调用指定分区的方法
        consumer.assign(topicPartitions);

        //消费数据
        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofSeconds(1));
            for (ConsumerRecord<String, String> stringStringConsumerRecord : poll) {
                System.out.println(stringStringConsumerRecord);
            }
        }
    }

}
